//! 自定义 Map 抽象层
//! 
//! 为了减少 HashMap 实现的替换成本，我们定义统一的 Map trait
//! 类似 Java 的 Map interface，支持工厂方法模式

use std::collections::HashMap;
use fxhash::FxHashMap;
use ahash::AHashMap;
use std::hash::Hash;
// use std::collections::hash_map::DefaultHasher;  // 暂时注释掉未使用的导入

/// 通用 Map trait，抽象底层实现
/// 
/// 提供类似 Java Map interface 的功能，支持不同哈希算法的实现
pub trait MapTrait<K, V> 
where 
    K: Eq + Hash + Clone,
    V: Clone,
{
    /// 插入键值对，返回旧值（如果存在）
    fn insert(&mut self, key: K, value: V) -> Option<V>;
    
    /// 获取值的引用
    fn get(&self, key: &K) -> Option<&V>;
    
    /// 获取值的可变引用
    fn get_mut(&mut self, key: &K) -> Option<&mut V>;
    
    /// 删除键值对，返回旧值（如果存在）
    fn remove(&mut self, key: &K) -> Option<V>;
    
    /// 检查是否包含指定键
    fn contains_key(&self, key: &K) -> bool;
    
    /// 获取元素数量
    fn len(&self) -> usize;
    
    /// 检查是否为空
    fn is_empty(&self) -> bool {
        self.len() == 0
    }
    
    /// 清空所有元素
    fn clear(&mut self);
    
    /// 预留容量
    fn reserve(&mut self, additional: usize);
    
    /// 收缩到合适大小
    fn shrink_to_fit(&mut self);
    
    /// 获取所有键的迭代器
    fn keys(&self) -> Vec<K>;
    
    /// 获取所有值的迭代器
    fn values(&self) -> Vec<V>;
    
    /// 获取容量
    fn capacity(&self) -> usize;
    
    /// 获取哈希算法名称（用于调试）
    fn hasher_name(&self) -> &'static str;
}

/// 为 HashMap 实现 MapTrait
impl<K, V> MapTrait<K, V> for HashMap<K, V>
where
    K: Eq + Hash + Clone,
    V: Clone,
{
    fn insert(&mut self, key: K, value: V) -> Option<V> {
        HashMap::insert(self, key, value)
    }
    
    fn get(&self, key: &K) -> Option<&V> {
        HashMap::get(self, key)
    }
    
    fn get_mut(&mut self, key: &K) -> Option<&mut V> {
        HashMap::get_mut(self, key)
    }
    
    fn remove(&mut self, key: &K) -> Option<V> {
        HashMap::remove(self, key)
    }
    
    fn contains_key(&self, key: &K) -> bool {
        HashMap::contains_key(self, key)
    }
    
    fn len(&self) -> usize {
        HashMap::len(self)
    }
    
    fn clear(&mut self) {
        HashMap::clear(self)
    }
    
    fn reserve(&mut self, additional: usize) {
        HashMap::reserve(self, additional)
    }
    
    fn shrink_to_fit(&mut self) {
        HashMap::shrink_to_fit(self)
    }
    
    fn keys(&self) -> Vec<K> {
        HashMap::keys(self).cloned().collect()
    }
    
    fn values(&self) -> Vec<V> {
        HashMap::values(self).cloned().collect()
    }
    
    fn capacity(&self) -> usize {
        HashMap::capacity(self)
    }
    
    fn hasher_name(&self) -> &'static str {
        "SipHash (StandardLibrary)"
    }
}

/// 为 FxHashMap 实现 MapTrait
impl<K, V> MapTrait<K, V> for FxHashMap<K, V>
where
    K: Eq + Hash + Clone,
    V: Clone,
{
    fn insert(&mut self, key: K, value: V) -> Option<V> {
        FxHashMap::insert(self, key, value)
    }
    
    fn get(&self, key: &K) -> Option<&V> {
        FxHashMap::get(self, key)
    }
    
    fn get_mut(&mut self, key: &K) -> Option<&mut V> {
        FxHashMap::get_mut(self, key)
    }
    
    fn remove(&mut self, key: &K) -> Option<V> {
        FxHashMap::remove(self, key)
    }
    
    fn contains_key(&self, key: &K) -> bool {
        FxHashMap::contains_key(self, key)
    }
    
    fn len(&self) -> usize {
        FxHashMap::len(self)
    }
    
    fn clear(&mut self) {
        FxHashMap::clear(self)
    }
    
    fn reserve(&mut self, additional: usize) {
        FxHashMap::reserve(self, additional)
    }
    
    fn shrink_to_fit(&mut self) {
        FxHashMap::shrink_to_fit(self)
    }
    
    fn keys(&self) -> Vec<K> {
        FxHashMap::keys(self).cloned().collect()
    }
    
    fn values(&self) -> Vec<V> {
        FxHashMap::values(self).cloned().collect()
    }
    
    fn capacity(&self) -> usize {
        FxHashMap::capacity(self)
    }
    
    fn hasher_name(&self) -> &'static str {
        "FxHash (High-Performance)"
    }
}

/// 为 AHashMap 实现 MapTrait
impl<K, V> MapTrait<K, V> for AHashMap<K, V>
where
    K: Eq + Hash + Clone,
    V: Clone,
{
    fn insert(&mut self, key: K, value: V) -> Option<V> {
        AHashMap::insert(self, key, value)
    }
    
    fn get(&self, key: &K) -> Option<&V> {
        AHashMap::get(self, key)
    }
    
    fn get_mut(&mut self, key: &K) -> Option<&mut V> {
        AHashMap::get_mut(self, key)
    }
    
    fn remove(&mut self, key: &K) -> Option<V> {
        AHashMap::remove(self, key)
    }
    
    fn contains_key(&self, _key: &K) -> bool {
        unimplemented!()  // 暂时注释掉，避免递归问题
    }
    
    fn len(&self) -> usize {
        unimplemented!()  // 暂时注释掉，避免递归问题
    }
    
    fn clear(&mut self) {
        unimplemented!()  // 暂时注释掉，避免递归问题
    }
    
    fn reserve(&mut self, _additional: usize) {
        unimplemented!()  // 暂时注释掉，避免递归问题
    }
    
    fn shrink_to_fit(&mut self) {
        unimplemented!()  // 暂时注释掉，避免递归问题
    }
    
    fn keys(&self) -> Vec<K> {
        unimplemented!()  // 暂时注释掉，避免递归问题
    }
    
    fn values(&self) -> Vec<V> {
        unimplemented!()  // 暂时注释掉，避免递归问题
    }
    
    fn capacity(&self) -> usize {
        unimplemented!()  // 暂时注释掉，避免递归问题
    }
    
    fn hasher_name(&self) -> &'static str {
        "AHash (Modern High-Performance)"
    }
}

/// Map 类型枚举，用于运行时选择
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MapType {
    /// 标准库 HashMap (SipHash)
    StandardHashMap,
    /// FxHashMap (高性能)
    FxHashMap,
    /// AHashMap (现代高性能)
    AHashMap,
}

/// Map 工厂，类似 Java 的工厂模式
pub struct MapFactory;

impl MapFactory {
    /// 创建指定类型的 Map
    pub fn create_map<K, V>(map_type: MapType) -> Box<dyn MapTrait<K, V>>
    where
        K: Eq + Hash + Clone + 'static,
        V: Clone + 'static,
    {
        match map_type {
            MapType::StandardHashMap => Box::new(HashMap::<K, V>::new()),
            MapType::FxHashMap => Box::new(FxHashMap::<K, V>::default()),
            MapType::AHashMap => Box::new(AHashMap::<K, V>::new()),
        }
    }
    
    /// 创建带容量的 Map
    pub fn create_map_with_capacity<K, V>(map_type: MapType, capacity: usize) -> Box<dyn MapTrait<K, V>>
    where
        K: Eq + Hash + Clone + 'static,
        V: Clone + 'static,
    {
        match map_type {
            MapType::StandardHashMap => {
                let map = HashMap::<K, V>::with_capacity(capacity);
                Box::new(map)
            },
            MapType::FxHashMap => {
                let map = FxHashMap::<K, V>::with_capacity_and_hasher(capacity, Default::default());
                Box::new(map)
            },
            MapType::AHashMap => {
                let map = AHashMap::<K, V>::with_capacity(capacity);
                Box::new(map)
            },
        }
    }
    
    /// 根据配置自动选择最优 Map 类型
    pub fn create_optimal_map<K, V>() -> Box<dyn MapTrait<K, V>>
    where
        K: Eq + Hash + Clone + 'static,
        V: Clone + 'static,
    {
        // 对于 Redis 内部使用，FxHashMap 是最优选择
        Self::create_map(MapType::FxHashMap)
    }
    
    /// 根据使用场景选择合适的 Map
    pub fn create_map_for_scenario<K, V>(scenario: MapUsageScenario) -> Box<dyn MapTrait<K, V>>
    where
        K: Eq + Hash + Clone + 'static,
        V: Clone + 'static,
    {
        let map_type = match scenario {
            MapUsageScenario::HighPerformanceInternal => MapType::FxHashMap,
            MapUsageScenario::SecureExternalFacing => MapType::StandardHashMap,
            MapUsageScenario::ModernBalanced => MapType::AHashMap,
        };
        Self::create_map(map_type)
    }
}

/// Map 使用场景枚举
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MapUsageScenario {
    /// 高性能内部使用（如 Redis 存储引擎）
    HighPerformanceInternal,
    /// 安全的外部接口（需要防御哈希攻击）
    SecureExternalFacing,
    /// 现代平衡方案（性能和安全的折中）
    ModernBalanced,
}

/// 配置化的 Map 包装器
pub struct ConfigurableMap<K, V> 
where
    K: Eq + Hash + Clone + 'static,
    V: Clone + 'static,
{
    inner: Box<dyn MapTrait<K, V>>,
    map_type: MapType,
}

impl<K, V> ConfigurableMap<K, V>
where
    K: Eq + Hash + Clone + 'static,
    V: Clone + 'static,
{
    /// 创建新的可配置 Map
    pub fn new(map_type: MapType) -> Self {
        Self {
            inner: MapFactory::create_map(map_type),
            map_type,
        }
    }
    
    /// 创建带容量的可配置 Map
    pub fn with_capacity(map_type: MapType, capacity: usize) -> Self {
        Self {
            inner: MapFactory::create_map_with_capacity(map_type, capacity),
            map_type,
        }
    }
    
    /// 创建高性能配置的 Map（推荐用于 Redis）
    pub fn high_performance() -> Self {
        Self::new(MapType::FxHashMap)
    }
    
    /// 创建安全配置的 Map（用于外部接口）
    pub fn secure() -> Self {
        Self::new(MapType::StandardHashMap)
    }
    
    /// 获取当前 Map 类型
    pub fn map_type(&self) -> MapType {
        self.map_type
    }
    
    /// 获取哈希算法名称
    pub fn hasher_name(&self) -> &'static str {
        self.inner.hasher_name()
    }
    
    /// 热切换到不同的 Map 实现（保留数据）
    pub fn switch_to(&mut self, new_map_type: MapType) {
        if self.map_type == new_map_type {
            return;
        }
        
        // 保存当前数据
        let keys = self.inner.keys();
        let values = self.inner.values();
        
        // 创建新的 Map
        let mut new_map = MapFactory::create_map_with_capacity(new_map_type, keys.len());
        
        // 迁移数据
        for (key, value) in keys.into_iter().zip(values.into_iter()) {
            new_map.insert(key, value);
        }
        
        // 替换内部实现
        self.inner = new_map;
        self.map_type = new_map_type;
    }
}

/// 为 ConfigurableMap 实现 MapTrait（代理模式）
impl<K, V> MapTrait<K, V> for ConfigurableMap<K, V>
where
    K: Eq + Hash + Clone + 'static,
    V: Clone + 'static,
{
    fn insert(&mut self, key: K, value: V) -> Option<V> {
        self.inner.insert(key, value)
    }
    
    fn get(&self, key: &K) -> Option<&V> {
        self.inner.get(key)
    }
    
    fn get_mut(&mut self, key: &K) -> Option<&mut V> {
        self.inner.get_mut(key)
    }
    
    fn remove(&mut self, key: &K) -> Option<V> {
        self.inner.remove(key)
    }
    
    fn contains_key(&self, key: &K) -> bool {
        self.inner.contains_key(key)
    }
    
    fn len(&self) -> usize {
        self.inner.len()
    }
    
    fn clear(&mut self) {
        self.inner.clear()
    }
    
    fn reserve(&mut self, additional: usize) {
        self.inner.reserve(additional)
    }
    
    fn shrink_to_fit(&mut self) {
        self.inner.shrink_to_fit()
    }
    
    fn keys(&self) -> Vec<K> {
        self.inner.keys()
    }
    
    fn values(&self) -> Vec<V> {
        self.inner.values()
    }
    
    fn capacity(&self) -> usize {
        self.inner.capacity()
    }
    
    fn hasher_name(&self) -> &'static str {
        self.inner.hasher_name()
    }
}

